from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *

from ui.Ui_script_manager_dialog import Ui_Dialog_script_manager
from app.window.private_script_editor_dialog import Private_script_editor_dialog
from app.window.private_script_new_dialog import Private_script_new_dialog
from app.window.msg_box import Msg_box
import time
from database.db import Database

class Script_manager_signal(QObject):

    delete_script = Signal(int)
    show_self = Signal(int)

    # 编辑脚本 发射给线程 由线程处理返回信号
    edit_script = Signal(int)

    update_device_id = Signal(int)


class Private_script_manager_dialog(QDialog):
    
    def __init__(self, parent=None):
        super(Private_script_manager_dialog, self).__init__(parent)
        self.ui = Ui_Dialog_script_manager()
        self.ui.setupUi(self)

        self.setWindowTitle('私有脚本管理器')
        self.ui.pushButton_search.hide()

        self.setModal(True)  # 设置窗体为模态窗口，必须为True
        self.setWindowFlags(Qt.WindowCloseButtonHint)  # 设置窗体仅显示关闭按钮
        

        self.msg = Msg_box(self)
        self.signal = Script_manager_signal()
        self.col_names = {}
        self.init_col_names()
        self.reg_hot_key()

        self.device_id = -1

        self.editor_dialog = Private_script_editor_dialog()
        self.editor_dialog.hide()
        self.new_dialog = Private_script_new_dialog()
        self.new_dialog.hide()


        self.ui.pushButton_new.clicked.connect(lambda:self.new_dialog.slot_show_self(self.device_id))


        self.new_dialog.signal.save_script.connect(self.slot_save_script)

        self.signal.edit_script.connect(self.editor_dialog.slot_show)

        self.editor_dialog.signal.update_script_data.connect(self.update_script_data)

    def reg_hot_key(self):
        self.short = QShortcut(QKeySequence('Ctrl+Q'), self)
        self.short.activated.connect(self.ui.pushButton_new.click)


    def init_col_names(self):
        # 获取列id
        max_col = self.ui.tableWidget.columnCount()
        for i in range(max_col):
            text = self.ui.tableWidget.horizontalHeaderItem(i).text()
            self.col_names[text] = i


    def get_script_list(self) -> list[dict]:
        db = Database()
        # 获取设备的私有脚本id
        script_id_list = db.select('private_script_device',['script_id'],f'device_id={self.device_id}')
        script_table = []
        for script_id in script_id_list:
            # 查询脚本数据
            script_data = db.select('scripts',['name','info'],f'id={script_id[0]}')
            data = {
                'id':script_id[0],
                'name':script_data[0][0],
                'info':script_data[0][1],
            }
            script_table.append(data)

        db.close_conn()
        return script_table

    def slot_show(self,device_id:int):
        self.device_id = device_id
        script_table = self.get_script_list()
        self.load_script(script_table)
        self.show()
  


    # 加载脚本
    def load_script(self,data:list[dict]):
        # 删除现有行
        for i in range(self.ui.tableWidget.rowCount(),-1,-1):
            self.ui.tableWidget.removeRow(i)
        # self.ui.tableWidget.clear()
        for row in data:
            # 创建一行
            max_row = self.ui.tableWidget.rowCount()
            self.ui.tableWidget.insertRow(max_row)
            # 填写数据
            self.ui.tableWidget.setItem(max_row,self.col_names['id'],QTableWidgetItem())
            self.ui.tableWidget.setItem(max_row,self.col_names['名称'],QTableWidgetItem())
            self.ui.tableWidget.setItem(max_row,self.col_names['描述'],QTableWidgetItem())
            self.ui.tableWidget.item(max_row,self.col_names['id']).setText(str(row['id']))
            self.ui.tableWidget.item(max_row,self.col_names['名称']).setText(row['name'])
            self.ui.tableWidget.item(max_row,self.col_names['描述']).setText(row['info'])
            # 操作按钮
            wid = QWidget()
            layout = QHBoxLayout(wid)
            btn_edit = QPushButton('编辑')
            btn_del = QPushButton('删除')
            layout.addWidget(btn_edit)
            layout.addWidget(btn_del)
            layout.setContentsMargins(0,0,0,0)
            layout.setSpacing(0)
            self.ui.tableWidget.setCellWidget(max_row,self.col_names['操作'],wid)
            # 连接信号
            btn_edit.clicked.connect(lambda:self.signal.edit_script.emit(int(row['id'])))
            btn_del.clicked.connect(lambda:self.slot_del_script(int(row['id'])))
            #禁止编辑
            self.ui.tableWidget.item(max_row, self.col_names['id']).setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
            self.ui.tableWidget.item(max_row, self.col_names['名称']).setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
            self.ui.tableWidget.item(max_row, self.col_names['描述']).setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)


    def slot_new_script(self):
        self.new_dialog.slot_show_self(self.device_id)
    


    def slot_del_script(self,script_id:int):
        db = Database()
        
        # 判断计划任务是否存在外键引用
        task_list = db.select('tasks',['id','name'],f'script_id={script_id}')
        if len(task_list) > 0:
            self.msg.msg_tips('计划任务中存在引用.删除对应计划任务后,再尝试')
            for data in task_list:
                print(data[0],data[1])
            db.close_conn()
            return

        # 删除private_script_device表项
        db.delete('private_script_device',f'script_id={script_id}')
        # 删除 scripts 表项
        db.delete('scripts',f'id={script_id}')
        db.close_conn()

        # 删除表格中的行
        for i in range(self.ui.tableWidget.rowCount()):
            if self.ui.tableWidget.item(i,self.col_names['id']).text() == str(script_id):
                self.ui.tableWidget.removeRow(i)
                break
        


    def slot_save_script(self,data:dict):
        # 创建一行
        max_row = self.ui.tableWidget.rowCount()
        self.ui.tableWidget.insertRow(max_row)
        # 填写数据
        self.ui.tableWidget.setItem(max_row,self.col_names['id'],QTableWidgetItem())
        self.ui.tableWidget.setItem(max_row,self.col_names['名称'],QTableWidgetItem())
        self.ui.tableWidget.setItem(max_row,self.col_names['描述'],QTableWidgetItem())
        self.ui.tableWidget.item(max_row,self.col_names['id']).setText(str(data['id']))
        self.ui.tableWidget.item(max_row,self.col_names['名称']).setText(data['name'])
        self.ui.tableWidget.item(max_row,self.col_names['描述']).setText(data['info'])
        # 操作按钮
        wid = QWidget()
        layout = QHBoxLayout(wid)
        btn_edit = QPushButton('编辑')
        btn_del = QPushButton('删除')
        layout.addWidget(btn_edit)
        layout.addWidget(btn_del)
        layout.setContentsMargins(0,0,0,0)
        layout.setSpacing(0)
        self.ui.tableWidget.setCellWidget(max_row,self.col_names['操作'],wid)
        # 连接信号
        btn_edit.clicked.connect(lambda:self.signal.edit_script.emit(int(data['id'])))
        btn_del.clicked.connect(lambda:self.slot_del_script(int(data['id'])))
        #禁止编辑
        self.ui.tableWidget.item(max_row, self.col_names['id']).setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
        self.ui.tableWidget.item(max_row, self.col_names['名称']).setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
        self.ui.tableWidget.item(max_row, self.col_names['描述']).setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
        # self.ui.tableWidget.item(max_row, self.col_names['操作']).setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)


    def update_script_data(self,script_id:int,data:dict):
        # 获取行号
        row = -1
        for i in range(self.ui.tableWidget.rowCount()):
            if self.ui.tableWidget.item(i,self.col_names['id']).text() == str(script_id):
                row = i
                break
        if row == -1 : return
        self.ui.tableWidget.item(row,self.col_names['名称']).setText(data['name'])
        self.ui.tableWidget.item(row,self.col_names['描述']).setText(data['info'])